//
//  BaseTopView.swift
//  GomroClient
//
//  Created by apple on 2019/12/8.
//  Copyright © 2019 cn.gomro.app. All rights reserved.
//

import UIKit

@objc protocol BaseTopViewDelegate {

    /** 开始搜索 */
    @objc optional func baseTopViewDidSearchFor(Paramas p:[String:Any])
    
    /** 取消搜索 */
    @objc optional func baseTopViewCancleSearch(isClean:Bool)
    
    /** 栏目切换 */
    @objc optional func baseTopSegmentedDidValueChange(currentMenu:String,currentIndex:Int)
}

/** 顶部视图基类 */
class BaseTopView: UIView {

    private let margin:CGFloat = 22
    private var arrTitles:[String]?
    private var strPlaceholder:String?
    
    weak var delegate:BaseTopViewDelegate?{
        didSet{
            self.topRightView.delegate = self.delegate
        }
    }
    private weak var pViewController:UIViewController?
    
    
    //MARK: - override
    init(WithTitles ts:[String]?,
         andPlaceHold ph:String?,
         andFrame rect:CGRect,
         andSearchData sd:[[String:Any]]?,
         andViewController vc:UIViewController?) {
        
        super.init(frame: rect)
        arrTitles = ts
        strPlaceholder = ph
        self.pViewController = vc
        
        if sd != nil && sd!.count > 0 {
            self.topRightView.arrSearch = sd
        }
    
        self.initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateConstraints() {
        
        self.segmentedView.snp.makeConstraints {[unowned self] make in
            make.left.right.equalTo(margin)
            make.right.equalTo(-margin)
            make.height.equalTo((self.arrTitles == nil || self.arrTitles!.count <= 0) ? 0 : 35)
            make.top.equalTo((self.arrTitles == nil || self.arrTitles!.count <= 0) ? 0 : 10)
        }
        
        if self.strPlaceholder != nil && self.strPlaceholder != "" {
            self.searchBar.snp.makeConstraints {[weak self] make in
                guard let self = self else { return }
                make.left.equalTo(margin)
                make.right.equalTo(-margin)
                make.top.equalTo(self.height - 45)
                make.height.equalTo(30)
            }
        }
        
        super.updateConstraints()
    }
    
    
    //MARK: - initView
    private func initView(){
        
        self.addSubview(self.segmentedView)
        
        if self.strPlaceholder != nil && self.strPlaceholder != "" {
            self.addSubview(self.searchBar)
        }
        
        if self.arrTitles == nil || arrTitles!.count <= 0 {
            self.segmentedView.isHidden = true
        }
        
        setNeedsUpdateConstraints()
    }
    
    
    //MARK: - 更新搜索信息
    func updateSearchInfo(Data d:[[String:Any]],andPlacehold p:String) {
        self.topRightView.arrSearch = d
        
        strPlaceholder = p
        if p != "" {
            self.searchBar.placeholder = p
        }
        self.topRightView.labTitle.text = p
    }
    
    
    //MARK: - 栏目切换
    @IBAction private func btnChangeAction(sender:UISegmentedControl) {
        let index = sender.selectedSegmentIndex
        let title = sender.titleForSegment(at: index)
        
        self.delegate?.baseTopSegmentedDidValueChange?(currentMenu: title!, currentIndex: index)
    }
    
    
    //MARK: - lazy load
    private lazy var topRightView:BaseTopRightView = {
        let _v = BaseTopRightView.init(frame: CGRect.init(x: 0, y: 0,width: 0.85 * K_APP_WIDTH,height: K_APP_HEIGHT))
        
        _v.labTitle.text = self.strPlaceholder
        _v.pViewController = self.pViewController
        
        return _v
    }()
    
    lazy var segmentedView:UISegmentedControl = {
        let _swc = BaseView.createSegmentedControlFor(Titles: self.arrTitles ?? [""],
                                                      andTintColor: K_APP_TINT_COLOR,
                                                      andSelectColot: UIColor.white,
                                                      andFont: UIFont.systemFont(ofSize: 15, weight: .bold),
                                                      andBGColor: UIColor.white)
        
        _swc.addTarget(self, action: #selector(btnChangeAction(sender:)), for: .valueChanged)
        
        return _swc
    }()

    lazy var searchBar:ANCustomTextField = {
        let _txt = ANCustomTextField.init()
        
        _txt.keyboardType = .default
        _txt.returnKeyType = .search
        
        //左边图标
        _txt.leftNormalImage = YYImage.init(named: "dmand_search_seek_gray")
        _txt.leftPadding = 32.6
        _txt.leftViewMode = .always
        
        _txt.delegate = self
        _txt.hasBorder = true
        _txt.hasBottomBorder = false
        
        _txt.borderStyle = .none
        _txt.layer.cornerRadius = 15
        _txt.layer.borderColor = UIColor.clear.cgColor
        
        let _bc:UIColor = {
            if #available(iOS 13.0, *) {
                let _c = UIColor.init { (traitCollection:UITraitCollection) -> UIColor in
                    if traitCollection.userInterfaceStyle == .dark {
                        return UIColor.init(hexString: "#2D2D2D")!
                    }
                    return UIColor.init().colorFromHexString(hex: "#F0F1F4")
                }
                return _c
            }
            return UIColor.init().colorFromHexString(hex: "#F0F1F4")
        }()
        _txt.backgroundColor = _bc
        
        //清除
        _txt.clearButtonMode = .whileEditing
        
        _txt.textColor = UIColor.init().colorFromHexString(hex: "#C9C9C9")
        _txt.font = UIFont.systemFont(ofSize: 13)
        
        //提示文本颜色
        _txt.placeholder = strPlaceholder
        _txt.attributedPlaceholder = Utils.shareInstance().setPlaceholderAttributeString(ForFullText: _txt.placeholder!,
                                                                                          ChangeText: _txt.placeholder!,
                                                                                      withChangeFont: _txt.font!,
                                                                                     withChangeColor: _txt.textColor,
                                                                                       isLineThrough: false)
        
        return _txt
    }()

}


//MARK: - UITextFilesDelegate
extension BaseTopView : UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        if textField == self.searchBar {
            if self.topRightView.isReload {
                self.topRightView.searchTableView.reloadData()
            }
            
            self.pViewController?.zh_popupController.layoutType = .right
            self.pViewController?.zh_popupController.slideStyle = .fromRight
            self.pViewController?.zh_popupController.allowPan = true
            self.pViewController?.zh_popupController.presentContentView(self.topRightView)
        }
        
        return false
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // [S] 禁止用户切换键盘为Emoji表情
        if textField.isFirstResponder {
            if textField.textInputMode?.primaryLanguage == "emoji" || textField.textInputMode?.primaryLanguage == nil {
                return false
            }
        }
        // [E] 禁止用户切换键盘为Emoji表情

        return true
    }
}

